package com.lh.自己动手写RPC;


import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 作者：idea
 * 日期：2018/7/2
 * 描述：
 */
public class ServerCenter implements Server {

    //设定一个线程池，用来存放相应的任务
    private static ExecutorService executorService= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static final HashMap<String,Class> serviceRegistry=new HashMap<String,Class>();

    private static boolean isRunning=false;

    private static int port;

    public ServerCenter(int port){
        this.port=port;
    }

    @Override
    public void stop() {
        executorService.shutdown();
        isRunning=false;

    }

    @Override
    public void start() throws IOException {
        ServerSocket serverSocket=new ServerSocket();
        serverSocket.bind(new InetSocketAddress(port));
        System.out.println("server start");
        isRunning=true;
        try{
        while(true){
            //每当有一个连接接入，就存放到线程池里面去
            executorService.execute(new ServiceTask(serverSocket.accept()));
            printAllService();
        }
        }catch (Exception e){

        }finally {
            serverSocket.close();
        }
    }

    @Override
    public void register(Class serviceInterface, Class impl) {
            this.serviceRegistry.put(serviceInterface.getName(),impl);
    }

    @Override
    public int getPort() {
        return port;
    }

    @Override
    public boolean isRunning() {
        return isRunning;
    }


    public void printAllService(){
        int index=1;
        for (String s : serviceRegistry.keySet()) {
            Class serviceName=serviceRegistry.get(s);
            System.out.println(index+"---"+serviceName.getName()+"--------");
            index++;
        }
    }

    private static class ServiceTask implements Runnable{

        Socket client=null;

        public ServiceTask(Socket client) {
            this.client=client;
        }


        @Override
        public void run() {
            ObjectOutputStream outputStream=null;
            ObjectInputStream inputStream=null;
            try {
                inputStream=new ObjectInputStream(client.getInputStream());
                String serviceName=inputStream.readUTF();
                String methodName=inputStream.readUTF();
                Class<?>[] parametersTypes= (Class<?>[]) inputStream.readObject();
                Object[] arguments= (Object[]) inputStream.readObject();
                Class serviceClass=serviceRegistry.get(serviceName);
                if(serviceClass==null){
                    throw new RuntimeException("class not exist!");
                }
                Method method=serviceClass.getMethod(methodName,parametersTypes);
                Object result=method.invoke(serviceClass.newInstance(),arguments);
                outputStream=new ObjectOutputStream(client.getOutputStream());
                outputStream.writeObject(result);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (client != null) {
                    try {
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
